#include "StringUtil.h"
#include <string>

using namespace std;

namespace helix
{
	string StringUtil::firstWord(string str)
	{
		unsigned int startWord = (unsigned int)str.find_first_not_of(WHITE_SPACE_CHARACTERS);
		if(startWord == str.npos)
			return "";

		unsigned int endWord = (unsigned int)str.find_first_of(WHITE_SPACE_CHARACTERS,startWord);
		if(endWord == str.npos)
			return str.substr(startWord);

		return str.substr(startWord,endWord-startWord-1);
	}


	string StringUtil::trim(string str)
	{
		unsigned int start = (unsigned int)str.find_first_not_of(WHITE_SPACE_CHARACTERS);
		if(start == str.npos)
			return "";
		
		unsigned int end = (unsigned int)str.find_last_not_of(WHITE_SPACE_CHARACTERS);
		if(end == str.npos)
			return str.substr(start);

		string retStr(str,start,end-start);

		return retStr;
	}

	int StringUtil::compareIgnoreCase(const string *s1, const string *s2)
	{
		string::const_iterator it1=s1->begin();
		string::const_iterator it2=s2->begin();

		//stop when either string's end has been reached
		while ( (it1!=s1->end()) && (it2!=s2->end()) ) 
		{ 
			if(toupper(*it1) < toupper(*it2)) //letters differ?
				return -1;
			else if(toupper(*it1) > toupper(*it2))
				return 1;
			it1++;
			it2++;
		}
		size_t size1=s1->size(), size2=s2->size();	// get the length of each string
		//return -1,0 or 1 according to strings' lengths
		if (size1<size2) 
			return -1;
		else if(size1>size2)
			return 1;

		return 0;
	}

	void StringUtil::replace(string *origString, const char *charsToReplace, const char *replaceWith)
	{
		string newString("");

		unsigned int size = origString->length();
		unsigned int currentIndex = 0;
		while(currentIndex<size)
		{
			unsigned int firstIndex = origString->find_first_of(charsToReplace,currentIndex);

			if(firstIndex == string::npos)
			{
				newString.append(origString->substr(currentIndex,size-currentIndex));
				currentIndex = size;
			}
			else
			{
				newString.append(origString->substr(currentIndex,firstIndex-currentIndex));
				newString.append(replaceWith);
				currentIndex = firstIndex + 1;
			}
		}

		origString->clear();
		origString->reserve(newString.size());
		origString->assign(newString);
	}

}